
import React, { useState,useEffect,useRef } from 'react';
import reactDom from 'react-dom';


//State hooks 代替class进行引用
const Example1=()=> {
  // 声明一个叫 “count” 的 state 变量。
  const [count, setCount] = useState(0);
  const [count1,setCount1] = useState('点击')
  return (
    <div>
      <p>你点击了 {count} 次</p>
      <button onClick={()=>{
        if(count==10){
          alert('你点啥')
          setCount(0)
        }
        if(count<10){
          setCount(count+1)
          setCount1('点击')
        }
      }}>
        {count1}
      </button>
    </div>
  );
}

//Effect hooks 调用或更新时加载
const Example2=()=>{
  const [count,setCount] = useState(0)

  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
    console.log(`You clicked ${count} times`)
  });

  return (
    <div>
      <p>你点击了 {count} 次</p>
      <button onClick={() => setCount(count + 1)}>
        点我
      </button>
    </div>
  )
}

//useRef 缓存
const Example3=()=>{

  const [counter, setCounter] = useState(0)
  const pre = useRef(null)

  return (
    <div>
      <p>当前值：{counter}</p>
      <p>之前的值：{/* `current` 指向已挂载到 DOM 上的文本输入元素*/ pre.current}</p>
      <button onClick={() => { pre.current = counter; setCounter(x => x + 1) }}>点我加</button>&nbsp;&nbsp;
      <button onClick={() => { pre.current = counter; setCounter(x => x - 1) }}>点我减</button>&nbsp;&nbsp;
      <button onClick={() => {console.log(pre.current)}}>查看Ref缓存</button>

    </div>
  )

}

reactDom.render(

  <>
  <h2>state hoooks</h2>
  <Example1/>
  <h2>Effect hoooks</h2>
  <Example2/>
  <h2>hooks useRef</h2>
  <Example3/>
  </>
  
,document.getElementById("root")
)